package unicall.em.services;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;

import unicall.em.dtos.MediaDto;
import unicall.em.models.Media;
import unicall.em.repositories.MediaRepository;
import unicall.em.utils.HttpClientUtil;
import unicall.em.utils.StringUtil;

@Service
public class MediaServiceImpl implements MediaService {

    @Autowired
    private MediaRepository repository;
    
    @Override
    public Media add(MediaDto dto) {
         Media media = new Media();
         media.setName(dto.getName());
         media.setFileName(dto.getFileName());
         media.setCategory(dto.getCategory());
         return repository.saveAndFlush(media);
    }
    
    
    public Media findById(String id){
        return repository.findOne(id);
    }

    public void deleteById(String id){
        repository.delete(id);
    }
    
    
    public Media update(MediaDto dto){
        String id = dto.getId();
        Media media = findById(id);
        media.setName(dto.getName());
        media.setFileName(dto.getFileName());
        media.setCategory(dto.getCategory());
        return repository.saveAndFlush(media);
    }

    @Override
    public JSONObject upload(Media media, String fileName) {
        String url=MEDIA_UPLOAD_URL;
        HttpClientUtil util = new HttpClientUtil();
        Map<String,String> params = new HashMap<String,String>();
        params.put("fileName", fileName);
        params.put("appId", "");
        JSONObject obj = null;
        try{
            String result = util.doPost(url, params);
            obj = JSONObject.parseObject(result);
            String fileId = obj.getString("fileId");
            String ucFileName = obj.getString("fileName");
            if(!StringUtil.isBlank(fileId)){
                media.setFileId(fileId);
                media.setFileAliasName(ucFileName);
                media.setState(Media.State.RSYNC.getState());
            }
        }catch(Exception e){
           media.setState(Media.State.ERROR.getState()); 
        }
        repository.saveAndFlush(media);
        return obj;
    }
    
    

    
    private final static String MEDIA_UPLOAD_URL="http://127.0.0.1:9011/media/upload";


    
    
   public Page<Media> findAll(Specification<Media> specification,Pageable pageable){
       return repository.findAll(specification, pageable);
   }


@Override
public List<Media> queryAll() {
    return repository.queryAll("USE");
}
    
    
    
}
